# pip install pymongo==4.6.3 sshtunnel==0.4.0
# python 11
from sshtunnel import SSHTunnelForwarder
from pymongo import MongoClient

# SSH配置
SSH_HOST = '192.168.1.1'  # SSH服务器地址
SSH_USERNAME = 'root'  # SSH登录用户名
SSH_PASSWORD = '123456'  # SSH登录密码
SSH_PORT = 22  # SSH端口，默认为22

# MongoDB配置
MONGO_HOST = '127.0.0.1'  # MongoDB服务器地址，通常是localhost
MONGO_DB = 'tasks'  # MongoDB数据库名称
MONGO_USER = 'tasks'  # MongoDB用户名
MONGO_PASS = 'admin123456!'  # MongoDB密码

# 本地用于转发的端口
LOCAL_BIND_PORT = 27017

with SSHTunnelForwarder(
        (SSH_HOST, SSH_PORT),
        ssh_username=SSH_USERNAME,
        ssh_password=SSH_PASSWORD,
        remote_bind_address=(MONGO_HOST, 27017),  # MongoDB默认端口为27017
        local_bind_address=('0.0.0.0', LOCAL_BIND_PORT)
) as tunnel:
    # 通过隧道连接MongoDB
    client = MongoClient(f'mongodb://{MONGO_USER}:{MONGO_PASS}@localhost:{tunnel.local_bind_port}/{MONGO_DB}')

    # 选择数据库和集合
    db = client[MONGO_DB]
    collection = db['test1']  # 替换为你的集合名称

    # 执行一些数据库操作
    for doc in collection.find():
        print(doc)

    # 关闭MongoDB连接
    client.close()

# 这里隧道会自动关闭